/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.order.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.order.dao.ProductDAO;
import com.javaeye.order.dao.PurchaseOrderDetailDAO;
import com.javaeye.order.dto.Product;
import com.javaeye.common.web.PageInfo;

public class ProductService implements IProductService {
	
	private static Log log = LogFactory.getLog(ProductService.class);
	
	private ProductDAO dao;
	
	private PurchaseOrderDetailDAO purchaseOrderDetailDao;
	
	public void setDao(ProductDAO dao) {
		this.dao = dao;
	}
	
	public void setPurchaseOrderDetailDao(PurchaseOrderDetailDAO purchaseOrderDetailDao) {
		this.purchaseOrderDetailDao = purchaseOrderDetailDao;
	}

	public List<Product> getAutoCompleteProducts(String name, int size) {
		List<Product> results = dao.getAutoCompleteProducts(name, size);
		if (results == null || results.size() == 0) {
			log.warn("在数据库中未找到产品数据");
		}
		return results;
	}

	@Override
	public Product getProduct(String id) {
		int intId = Integer.parseInt(id);
		Product product = dao.getProduct(intId);
		if (product == null) {
			log.warn("在数据库中未找到指定的产品  id：" + id);
		}
		return product;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getProductList(Product condition, PageInfo pageInfo) {
		List results = dao.getPageData(condition, pageInfo);
		if (results == null || results.size() == 0) {
			log.warn("在数据库中未找到产品数据");
		}
		return results;
	}

	@Override
	public boolean removeProduct(String id) {
		int intId = Integer.parseInt(id);
		//如果在别的地方使用了就不能删除
		long count = purchaseOrderDetailDao.getCountByProductId(intId);
		if (count > 0) {
			return false;
		}
		dao.removeProduct(intId);
		return true;
	}

	@Override
	public boolean saveProduct(Product product) {
		if (product.getId() == 0) {
			boolean isExist = dao.isExistProduct(product);
			if (isExist) {
				return false;
			}
		}
		dao.saveProduct(product);
		return true;
	}

}
